import React from 'react'
import ReactDom from 'react-dom'
import './index.css'

function Square(props:any) {
  return(
    <button 
      className={`square ${props.winner ? 'light' : ''}`}
      onClick={() => props.onClick()}>
      {props.value}
    </button>
  )
}

function calculateWinner(squares:Array<number>) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ]
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return lines[i]
    }
  }
  return null
}

function correspondingOrder(i:number){
  let h = Math.floor(i / 3)
  let r = i % 3
  let h_r = '(' + h + ',' + r + ')'
  return h_r
}

class Board extends React.Component<any>{
  renderSquare(i:number, isWinner:boolean) {
    return (
      <Square 
        key={i}
        value={this.props.squares[i]} 
        winner={isWinner}
        onClick={() => {this.props.onClick(i)}}/>
    )
  }
  render() {
    const boardRow = Array.from({length:3}, (v,k) => k)
    const boardCol = Array.from({length:3}, (v,k) => k)
    let squareIndex = -1
    const boardDiv = boardRow.map((row) => 
      <div className="board-row" key={row}>
        {boardCol.map(() => {
          squareIndex++
          let isWin = false
          let winnerList = this.props.winner
          if (winnerList) {
            for (let k = 0; k < winnerList.length; k++) {
              if (winnerList[k] === squareIndex) {
                isWin = true
                break
              }
            }
          }
          return this.renderSquare(squareIndex, isWin)
        })}
      </div>
    )
    return (
      <div>
        {boardDiv}
      </div>
    )
  }
}

interface IState {
  history: Array<any>,
  xIsNext: boolean,
  stepNumber: number,
  stepIndex: any,
  isAscending: boolean,
  winnerLine: Array<number>
}
class Game extends React.Component<any, IState>{
  constructor(props:IState) {
    super(props)
    this.state = {
      history: [{
        squares: Array(9).fill(null),
      }],
      xIsNext: true,
      stepNumber: 0,
      stepIndex: null,
      isAscending: true,
      winnerLine: []
    }
  }
  handleClick(i:number) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1)
    const current = history[this.state.stepNumber]
    const squares = current.squares.slice()
    if (calculateWinner(squares) || squares[i]) {
      return
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O'
    this.setState({
      history: history.concat([{
        squares: squares,
        stepIndex: i
      }]),
      xIsNext: !this.state.xIsNext,
      stepNumber: history.length,
    })
  }
  jumpTo(step:number){
    console.log('step', step)
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0
    })
  }
  handleSort(){
    this.setState({
      isAscending: !this.state.isAscending,
    })
  }
  render() {
    const history = this.state.history.slice()
    const current = history[this.state.stepNumber]
    const winner = calculateWinner(current.squares)
    if (!this.state.isAscending) {
      history.reverse()
    }
    const moves = history.map((step:any, move:number) => {
      const cor = correspondingOrder(step.stepIndex)
      let desc, moveIndex:number
      if (this.state.isAscending) {
        moveIndex = move
        desc = move ? 'Go to move #' + move + cor : 'Go to start'
      } else {
        moveIndex = history.length - move - 1
        desc = move === history.length - 1 ? 'Go to start' : 'Go to move #' + moveIndex + cor
      }
      return (
        <li key={move}>
          <button className={this.state.stepNumber === moveIndex ? 'active' : 'null'} onClick={() => this.jumpTo(moveIndex)}>{desc}</button>
        </li>
      )
    })
    const sortTxt = this.state.isAscending ? '升序' : '降序'
    let status
    if (winner) {
      status = 'Winner is ' + current.squares[winner[0]]
    } else {
      if (history.length > 9) {
        status = 'OH, It ends in a draw!'
      } else {
        status = 'Next Player is ' + (this.state.xIsNext ? 'X' : 'O')
      }
    }
    return (
      <div className="game">
        <div className="game-board">
          <Board 
            squares = {current.squares}
            winner = {winner}
            onClick={(i:number) => this.handleClick(i)} />
        </div>

        <div className="game-info">
          <div>{status}</div>
          <button onClick={() => this.handleSort()}>{sortTxt}</button>
          <ol>{moves}</ol>
        </div>
      </div>
    )
  }
}

ReactDom.render(
  <Game />,
  document.getElementById('root')
)